package smetana.modules.ui.form;

import com.google.common.base.Preconditions;
import org.apache.pivot.wtk.Component;
import org.apache.pivot.wtkx.WTKXSerializer;

/**
 * @author dmitry.mamonov
 */
public abstract class AbstractPanel {
    protected WTKXSerializer wtkx;
    private Component rootComponent;
    private boolean initialized = false;
    private Class panelClass;

    protected AbstractPanel() {
        this(null);
    }

    protected AbstractPanel(final Class panelClass) {
        this.panelClass = panelClass != null ? panelClass : getClass();
    }

    protected abstract void init();

    protected final void initialize() {
        if (initialized == false) {
            initialized = true;
            initializeComponent();
            init();
        }
    }

    private void initializeComponent(){
        String resource = "/" + panelClass.getName().replace('.', '/') + ".wtkx";
        System.out.println("resource: " + resource);
        Preconditions.checkNotNull(resource, "Resource is required");
        wtkx = new WTKXSerializer();
        try {
            rootComponent = (Component) wtkx.readObject(this, resource);
            Preconditions.checkNotNull(rootComponent, "Empty resource?: " + resource);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        wtkx.bind(this);
    }

    public Component getComponent() {
        initialize();
        return rootComponent;
    }
}
